<template>
  <view class="container">
    <!-- 封面图 -->
    <view class="section">
      <view class="row-between">
        <view class="row-text">
          <text class="label">更换直播封面图</text>
          <text class="tip tip-text">*建议上传1280*720，比例16:9</text>
        </view>
        <view class="cover-img-wrap" @click="onChangeCover">
          <image class="cover-img" :src="livesetting.cover || '/static/img.png'" mode="aspectFill"></image>
          <uni-icons type="right" size="24" color="#ccc"></uni-icons>
        </view>
      </view>
    </view>
    <!-- 直播标题 -->
    <view class="section">
      <view class="row-between">
        <text class="label">更换直播标题</text>
        <input class="input-no-bg" v-model="livesetting.title" :placeholder="'请输入标题'" />
      </view>
    </view>
    <!-- 直播描述 -->
    <view class="section">
      <view class="label">直播描述</view>
      <textarea class="textarea" placeholder="这个人很神秘，什么都没有写" v-model="livesetting.desc" />
    </view>
    <!-- 直播欢迎词 -->
    <view class="section">
      <view class="label">直播欢迎词</view>
      <textarea class="textarea" placeholder="例如：宝子们欢迎来到唐太医直播间" v-model="livesetting.welcome_word" />
    </view>
    <!-- 修改按钮 -->
    <view class="btn-wrap">
      <button class="submit-btn" @click="onSubmit">确定修改</button>
    </view>
  </view>
</template>

<script>
// 接口 api/live/setLiveInfo    live_title标题 live_cover封面 live_desc描述 live_welcome_word欢迎词
import { post } from '@/utils/request.js';
export default {
  data() {
    return {
      livesetting: {
        id: '',
        cover: '',
        title: '',
        desc: '',
        welcome_word: ''
      }
    };
  },
  onLoad(options) {
    this.livesetting = JSON.parse(decodeURIComponent(options.liveInfo)) || this.livesetting;

    const savedCover = uni.getStorageSync('live_cover');
    if (savedCover) {
      console.log('从本地存储获取的封面路径:', savedCover);
      // 验证路径有效性
      uni.getSavedFileInfo({
        filePath: savedCover,
        success: () => {
          this.livesetting.cover = savedCover; // 路径有效则更新封面
        },
        fail: (err) => {
          console.error('封面路径无效，清除缓存:', err);
          uni.removeStorageSync('live_cover');
        }
      });
    }
  },
  methods: {
    onChangeCover() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album'],
        success: (res) => {
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            const tempFilePath = res.tempFilePaths[0];
            // 持久化存储图片
            uni.saveFile({
              tempFilePath: tempFilePath,
              success: (saveRes) => {
                const savedFilePath = saveRes.savedFilePath;
                this.livesetting.cover = savedFilePath;
                uni.setStorageSync('live_cover', savedFilePath); // 缓存封面路径
                uni.showToast({ title: '封面上传成功', icon: 'success' });
              },
              fail: (err) => {
                console.error('保存图片失败，使用临时路径:', err);
                this.livesetting.cover = tempFilePath; // 失败时使用临时路径
              }
            });
          }
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({ title: '选择图片失败', icon: 'error' });
        }
      });
    },
    onSubmit() {
      const { id, title, cover, desc, welcome_word } = this.livesetting;

      // 表单验证
      if (!title) {
        return uni.showToast({ title: '请输入标题', icon: 'none' });
      }
      if (!cover) {
        return uni.showToast({ title: '请上传封面', icon: 'none' });
      }
      if (!desc) {
        return uni.showToast({ title: '请输入描述', icon: 'none' });
      }
      if (!welcome_word) {
        return uni.showToast({ title: '请输入欢迎词', icon: 'none' });
      }
      if (title.length > 100) {
        return uni.showToast({ title: '标题长度不能超过100个字符', icon: 'none' });
      }

      // 提交接口
      post('/api/live/setLiveInfo', {
        id,
        live_title: title,
        live_cover: cover,
        live_desc: desc,
        live_welcome_word: welcome_word
      }).then(res => {
        // console.log("参数", id, title, cover, desc, welcome_word)
        // console.log('修改成功:', res);
        // 提交成功后清除封面缓存（避免下次加载错误路径）
        uni.removeStorageSync('live_cover');
        uni.navigateBack({ url: '/pages/start/start' });
      }).catch(err => {
        console.error('修改失败:', err);
        uni.showToast({ title: '修改失败，请重试', icon: 'error' });
      });
    }
  }
};
</script>

<style scoped>
.container {
  background: #F6F6F8;
  max-height: 100vh;
}

.section {
  background: #fff;
  margin-top: 20rpx;
  padding: 40rpx 20rpx 20rpx 20rpx;
  border-radius: 16rpx;
}

.row-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.row-text {
  display: grid;
}

.cover-img-wrap {
  display: flex;
  align-items: center;
}

.label {
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
}

.tip {
  font-size: 22rpx;
  color: #bbb;
  margin-left: 20rpx;
}

.tip-text {
  margin: 3px 0px 0px 0px;
}

.cover-img {
  width: 180rpx;
  height: 100rpx;
  border-radius: 12rpx;
  background: #eee;
  margin-right: 20rpx;
}

.textarea {
  min-height: 100rpx;
  background: #f6f6f6;
  border-radius: 22rpx;
  margin-top: 20rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #D9D9D9;
}

.btn-wrap {
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 40rpx;
  display: flex;
  justify-content: center;
  z-index: 10;
}

.submit-btn {
  width: 80vw;
  height: 90rpx;
  background: linear-gradient(90deg, #ff7c2d, #ff4e2d);
  color: #fff;
  font-size: 34rpx;
  border-radius: 50rpx;
  font-weight: bold;
  box-shadow: 0 8rpx 24rpx rgba(255, 124, 45, 0.15);
  border: none;
}

.input-no-bg {
  background: transparent;
  border: none;
  font-size: 30rpx;
  color: #999;
  text-align: right;
  width: 300rpx;
}
</style>